package com.dayuanit.dy17.atm.atmbackoffice.service.impl;

import com.dayuanit.dy17.atm.atmbackoffice.entity.Role;
import com.dayuanit.dy17.atm.atmbackoffice.entity.User;
import com.dayuanit.dy17.atm.atmbackoffice.exception.BizException;
import com.dayuanit.dy17.atm.atmbackoffice.mapper.RoleMapper;
import com.dayuanit.dy17.atm.atmbackoffice.mapper.UserMapper;
import com.dayuanit.dy17.atm.atmbackoffice.service.IRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void createRole(String roleKey, String roleValue) {
        if (StringUtils.isBlank(roleKey) || StringUtils.isBlank(roleValue)) {
            throw new BizException("有必填参数为空");
        }

        Role role = new Role();
        role.setRoleKey(roleKey);
        role.setRoleValue(roleValue);
        roleMapper.insert(role);
    }

    @Transactional
    @Override
    public void addUserRefRole(String username, Long[] roleIds) {
        User user = userMapper.getByUsername(username);
        if (null == user) {
            throw new BizException("用户不存在");
        }

        for (Long roleId : roleIds) {
            roleMapper.insertUserRefRole(user.getId(), roleId);
        }
    }

    @Override
    public List<Role> loadRoles() {
        return roleMapper.listRoles();
    }

    @Override
    public List<Role> loadRoles(Long userId) {
        return roleMapper.listRolesByUserId(userId);
    }
}
